package org.lonetree.tc.core.id;

import org.lonetree.tc.core.id.ValidatedIdentifier.ValidationException;


/**
 * An InternalIdentifiableItem is one that has no natural way to identify it,
 * but still needs to be identified by a ValidatedIdentifier. It can be
 * constructed with null identifier since creators of an object are not likely
 * to be aware of a sensical identifier to assign to the item. In this case, the
 * item will be assigned a TempId and getIdentifier() will return that TempId.
 */
public abstract class InternalIdentifiableItem extends IdentifiableItem{

	private NumericalId identifier;
	
	protected InternalIdentifiableItem(NumericalId identifier){
		this.identifier = identifier;
		if(identifier == null)
			try{
				this.identifier = new TempId();
			}
			catch(ValidationException e){
				e.printStackTrace();
			}
	}
	
	@Override
	protected NumericalId getIdentifier(){
		return identifier;
	}
	
	protected void setIdentifier(NumericalId identifier){
		checkIdentifier(identifier);
		this.identifier = identifier;
	}

	/**
	 * A TempId represents a temporary identifier for an
	 * InternalIdentifiableItem. The item should have its identifier replaced
	 * with a permanent one by the persistance layer when it is persisted.
	 */
	public static class TempId extends NumericalId{
		private static long tempid = -1;
		public TempId() throws ValidationException{
			super(tempid, INFINITE_LENGTH_ALLOWED);
			tempid--;
		}
	}
}
